package ar.uade.edu.fain.ad.server.util.persistence;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateTransactionManager implements TransactionManager {

	private static HibernateTransactionManager instance;
	
	private HibernateTransactionManager() {
		super();
	}
	
	public static HibernateTransactionManager get() {
		if (instance == null) {
			instance = new HibernateTransactionManager();
		} 
		return instance;
	}
	
	private Session getSession() {
		return HibernateUtil.get().getSession();
	}

	@Override
	public void start() {
		final Session session = getSession();
		final Transaction transaction = session.getTransaction();
		if (transaction == null || !transaction.isActive()) {
			session.beginTransaction();
		}
	}

	@Override
	public void rollback() {
		try {
			final Session session = getSession();
			final Transaction transaction = session.getTransaction();
			if (transaction != null
					&& transaction.isActive()
					&& !transaction.wasCommitted() 
					&& !transaction.wasRolledBack()) {
				transaction.rollback();
			}
			if (session.isOpen()) {
				session.close();
			}
		} catch (HibernateException e) {
			System.err.println(
					"(" + getClass().getSimpleName() + ") - Silenced: " 
					+ e.getMessage());
			e.printStackTrace(System.err);
		}
	}

	@Override
	public void commit() {
		final Session session = getSession();
		final Transaction transaction = session.getTransaction();
		if (transaction != null
				&& transaction.isActive()
				&& !transaction.wasCommitted() 
				&& !transaction.wasRolledBack()) {
			transaction.commit();
		}
		if (session.isOpen()) {
			session.close();
		}
	}

}
